const { body, param } = require('express-validator')
const validate = require('../middleware/validate')
const Navigation = require('../models/Navigation')
const mongoose = require('mongoose')
const Category = require('../models/Category')


//添加导航
exports.addNavigation = validate([
  body("navigation_link").notEmpty().withMessage("导航链接不能为空"),
  body("navigation_name").notEmpty().withMessage("导航名称不能为空"),
  body("navigation_name").custom(async (value) => {
    // 查询是否有这个导航
    const navigation = await Navigation.findOne({ navigation_name: value });
    if (navigation) {
      return Promise.reject("导航已经存在");
    }
    return true;
  })
]);

//删除导航

exports.delNavigation = validate([
  param('id').not().isEmpty().withMessage('ID 是必需的'),
  param('id')
    .custom((value, { req }) => {
      return mongoose.Types.ObjectId.isValid(value)
    })
    .withMessage('ID 必须是有效的MongoDB ObjectId'),
  param('id').custom(async (value) => {
    // 查询是否有这个分类
    const category = await Navigation.findById(value)
    if (!category) {
      return Promise.reject('导航不存在')
    }
    return true
  }),
])

//修改导航
exports.updateNavigation = validate([
  param('id').not().isEmpty().withMessage('ID是必需的'),
  param('id')
    .custom((value, { req }) => {
      return mongoose.Types.ObjectId.isValid(value)
    })
    .withMessage('ID 必须是有效的MongoDB ObjectId'),
  body("navigation_link").notEmpty().withMessage("导航链接不能为空"),
  body("navigation_name").notEmpty().withMessage("导航名称不能为空"),
  body("navigation_icon").notEmpty().withMessage("导航图片不能为空"),
])
